package com.example.airkiss.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class JsAPIConfigHandle {

    @Autowired
    private HttpConnection httpConnection;

    /**
     * 生成JsAPIConfig
     * @Title: createConfig
     * @Description: TODO
     * @param @param link 使用AirKiss的链接地址
     * @param @return
     * @param @throws Exception
     * @return JsAPIConfig
     * @throws
     */
    public JsAPIConfig createConfig(String link) throws Exception {
        JsAPIConfig config = new JsAPIConfig();
        config.setLink(link);
        String nonce = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String src = "jsapi_ticket=" + getJsTicketFromWechat() + "&noncestr="
                + nonce + "&timestamp=" + timestamp + "&url="
                + config.getLink();
        String signature = SHAEncryptor.sha1(src);

        config.setAppId(WXConstants.WX_APPID);
        config.setDebug(true);
        config.setNonce(nonce);
        config.setTimestamp(timestamp);
        config.setSignature(signature);
        return config;
    }

    /**
     * 获取jsTicket
     * @Title: getJsTicketFromWechat
     * @Description: TODO
     * @param @return
     * @param @throws Exception
     * @return String
     * @throws
     */
    public  String getJsTicketFromWechat() throws Exception{
        String accessToken = AccessTokenInfo.accessToken.getAccessToken();
        String responeText = httpConnection.get(WXConstants.TICKET_UTL+accessToken);
        JSONObject resJson = JSON.parseObject(responeText);
        String jsTicket = resJson.getString("ticket");
        return jsTicket;
    }
}
